package com.jinzheng.nettytestss.lisent;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;

/**
 * kafka消费器
 */
@Slf4j
@Component
public class MyConsumer {

    /**
     * 监听自定义配置消费
     * @param records
     * @param ack
     */
    @KafkaListener(topics = "my-replicated-topic", groupId = "MyGroup1", containerFactory = "kafkaListenerContainerFactory")
    public void kafkalistener(List<ConsumerRecord<?, ?>> records, Acknowledgment ack){
        for(ConsumerRecord item:records) {
            System.out.printf("topic is %s, offset is %d,partition is %s, value is %s \n", item.topic(), item.offset(),item.partition(), item.value());
        }
        ack.acknowledge();
    }

    /**
     * 监听单个topic消费
     * @param record
     * @param headername
     * @param acknowledgment
     */
    @KafkaListener(topics = {"tesdsea"},groupId = "{spring.kafka.groupid:jinzheng_kakfa_value:sdfsas}")
    public void handMessage(ConsumerRecord<String, String> record ,@Header("header_name") String headername,Acknowledgment acknowledgment){
        String topic = record.topic();
        String msg = record.value();
        log.info("消费者接受消息：topic-->"+topic+",msg->>"+msg+",header_name->>"+headername);
//        try {
//            acknowledgment.acknowledge();
//        }catch (Exception ex){
//            log.error("解析提取数据发生错误："+ex.getMessage(),ex);
//        }
    }

    /**
     * 监听多个topic消费
     * @param record
     * @param headername
     * @param acknowledgment
     */
    @KafkaListener(topics = "#{'${spring.kafka.topics:test_sdfs_topic}'.split(',')}",groupId = "${spring.kafka.groupId:trrdsdas}",concurrency = "2")
    public void handMessages(ConsumerRecord<String, String> record ,@Header("header_name") String headername,Acknowledgment acknowledgment){
        Optional<?> kafkaMessage = Optional.ofNullable(record.value());
        if (kafkaMessage.isPresent()) {
            Object message = kafkaMessage.get();
            log.info("----------------- record =" + record);
            log.info("----------------- message =" + message);
        }
    }

}
